<template>
  <div class="resource-self-management">
    <Tabs v-model:active-key="activeTab">
      <!-- 基础信息 -->
      <TabPane key="basic" tab="基础信息">
        <div class="tab-content">
          <ResourceBasicInfo :resource="resource" @edit="handleBasicInfoEdit" />
        </div>
      </TabPane>

      <!-- 属性管理 -->
      <TabPane key="properties" tab="属性管理">
        <ResourcePropertyTab
          :resource="resource"
          @property-update="handlePropertyUpdate"
        />
      </TabPane>

      <!-- 能力管理 -->
      <TabPane key="capabilities" tab="能力管理">
        <ResourceCapabilityTab
          :resource="resource"
          @capabilityUpdate="handleCapabilityUpdate"
          @editCapability="handleEditCapability"
        />
      </TabPane>

      <!-- 状态管理 -->
      <TabPane key="status" tab="状态管理">
        <ResourceStatusManagement
          :resource-id="resource.id"
          :resource-type="resource.resource_type"
        />
      </TabPane>

      <!-- 行为管理 -->
      <TabPane key="behavior" tab="行为管理">
        <BehaviorManagement
          :resource-id="resource.id"
          :resource-type="resource.resource_type"
        />
      </TabPane>

      <!-- 事件管理 -->
      <TabPane key="event" tab="事件管理">
        <EventManagement
          :resource-id="resource.id"
          :resource-type="resource.resource_type"
        />
      </TabPane>

      <!-- 交易管理 -->
      <TabPane key="trading" tab="交易管理">
        <div class="tab-content">
          <div class="section-header">
            <h3>交易配置</h3>
            <div class="header-actions">
              <Button @click="showTradingGuide">
                <IconifyIcon icon="ant-design:question-circle-outlined" />
                交易指南
              </Button>
              <Button type="primary" @click="configureTrading">
                <IconifyIcon icon="ant-design:transaction-outlined" />
                配置交易
              </Button>
            </div>
          </div>

          <!-- 定价策略 -->
          <div class="pricing-section">
            <h4>定价策略</h4>
            <Row :gutter="16">
              <Col :span="8">
                <Card title="成本价格">
                  <Statistic
                    title="基础成本"
                    :value="tradingData.costPrice"
                    prefix="¥"
                  />
                  <Statistic
                    title="运营成本"
                    :value="tradingData.operationalCost"
                    prefix="¥"
                  />
                </Card>
              </Col>
              <Col :span="8">
                <Card title="交易价格">
                  <Statistic
                    title="标准价格"
                    :value="tradingData.standardPrice"
                    prefix="¥"
                  />
                  <Statistic
                    title="优惠价格"
                    :value="tradingData.discountPrice"
                    prefix="¥"
                  />
                </Card>
              </Col>
              <Col :span="8">
                <Card title="订阅价格">
                  <Statistic
                    title="月订阅"
                    :value="tradingData.monthlyPrice"
                    prefix="¥"
                  />
                  <Statistic
                    title="年订阅"
                    :value="tradingData.yearlyPrice"
                    prefix="¥"
                  />
                </Card>
              </Col>
            </Row>
          </div>

          <!-- 交易对象 -->
          <div class="trading-partners">
            <h4>交易合作对象</h4>
            <div class="partners-grid">
              <div
                v-for="partner in tradingPartners"
                :key="partner.id"
                class="partner-item"
              >
                <IconifyIcon :icon="getPartnerTypeIcon(partner.type)" />
                <div class="partner-info">
                  <div class="partner-name">{{ partner.name }}</div>
                  <div class="partner-type">{{ partner.type }}</div>
                </div>
                <Tag :color="partner.status === 'active' ? 'green' : 'orange'">
                  {{ partner.status === 'active' ? '活跃' : '暂停' }}
                </Tag>
              </div>
            </div>
          </div>

          <!-- 交易历史 -->
          <div class="trading-history">
            <h4>交易历史</h4>
            <Table
              :columns="tradingColumns"
              :data-source="tradingHistory"
              :pagination="false"
            />
          </div>
        </div>
      </TabPane>

      <!-- 事件联动 -->
      <TabPane key="events" tab="事件联动">
        <div class="tab-content">
          <div class="section-header">
            <h3>事件联动配置</h3>
            <Button type="primary" @click="configureEventLinkage">
              <IconifyIcon icon="ant-design:link-outlined" />
              配置联动
            </Button>
          </div>

          <!-- 触发事件 -->
          <div class="trigger-events">
            <h4>触发事件</h4>
            <div class="events-grid">
              <div
                v-for="event in triggerEvents"
                :key="event.id"
                class="event-item"
              >
                <div class="event-header">
                  <IconifyIcon :icon="getEventTypeIcon(event.type)" />
                  <span class="event-name">{{ event.name }}</span>
                  <Tag :color="event.status === 'active' ? 'green' : 'red'">
                    {{ event.status === 'active' ? '启用' : '禁用' }}
                  </Tag>
                </div>
                <div class="event-description">{{ event.description }}</div>
                <div class="event-conditions">
                  <div
                    class="condition-item"
                    v-for="condition in event.conditions"
                    :key="condition.id"
                  >
                    <span class="condition-label">{{ condition.field }}:</span>
                    <span class="condition-value"
                      >{{ condition.operator }} {{ condition.value }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 联动规则 -->
          <div class="linkage-rules">
            <h4>联动规则</h4>
            <div class="rules-list">
              <div
                v-for="rule in linkageRules"
                :key="rule.id"
                class="rule-item"
              >
                <div class="rule-header">
                  <IconifyIcon :icon="getRuleTypeIcon(rule.type)" />
                  <span class="rule-name">{{ rule.name }}</span>
                  <Tag :color="rule.status === 'active' ? 'green' : 'orange'">
                    {{ rule.status === 'active' ? '活跃' : '暂停' }}
                  </Tag>
                </div>
                <div class="rule-description">{{ rule.description }}</div>
                <div class="rule-actions">
                  <div
                    class="action-item"
                    v-for="action in rule.actions"
                    :key="action.id"
                  >
                    <IconifyIcon :icon="getActionTypeIcon(action.type)" />
                    <span
                      >{{ action.targetResource }} - {{ action.action }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 绑定组件管理 -->
      <TabPane key="components" tab="绑定组件">
        <div class="tab-content">
          <div class="section-header">
            <h3>已绑定组件</h3>
            <Button type="primary" @click="bindComponent">
              <IconifyIcon icon="ant-design:link-outlined" />
              绑定组件
            </Button>
          </div>
          <div class="components-list">
            <div
              v-for="component in boundComponents"
              :key="component.id"
              class="component-item"
            >
              <IconifyIcon :icon="getComponentIcon(component.type)" />
              <span>{{ component.name }}</span>
              <Tag :color="component.status === 'active' ? 'green' : 'orange'">
                {{ component.status === 'active' ? '活跃' : '待激活' }}
              </Tag>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 授权管理 -->
      <TabPane key="authorization" tab="授权管理">
        <div class="tab-content">
          <div class="section-header">
            <h3>访问授权</h3>
            <Button type="primary" @click="grantAuthorization">
              <IconifyIcon icon="ant-design:safety-outlined" />
              授权访问
            </Button>
          </div>
          <div class="authorization-list">
            <div
              v-for="auth in authorizations"
              :key="auth.id"
              class="authorization-item"
            >
              <IconifyIcon :icon="getAuthTypeIcon(auth.type)" />
              <span>{{ auth.name }}</span>
              <Tag :color="auth.status === 'active' ? 'green' : 'red'">
                {{ auth.status === 'active' ? '有效' : '已过期' }}
              </Tag>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 委托管理 -->
      <TabPane key="delegation" tab="委托管理">
        <div class="tab-content">
          <div class="section-header">
            <h3>委托关系</h3>
            <Button type="primary" @click="createDelegation">
              <IconifyIcon icon="ant-design:user-switch-outlined" />
              创建委托
            </Button>
          </div>
          <div class="delegation-list">
            <div
              v-for="delegation in delegations"
              :key="delegation.id"
              class="delegation-item"
            >
              <IconifyIcon :icon="getDelegationTypeIcon(delegation.type)" />
              <span>{{ delegation.name }}</span>
              <Tag :color="delegation.status === 'active' ? 'green' : 'orange'">
                {{ delegation.status === 'active' ? '活跃' : '暂停' }}
              </Tag>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 监控管理 -->
      <TabPane key="monitoring" tab="监控管理">
        <div class="tab-content">
          <div class="section-header">
            <h3>资源监控</h3>
            <Button type="primary" @click="configureMonitoring">
              <IconifyIcon icon="ant-design:dashboard-outlined" />
              配置监控
            </Button>
          </div>
          <Row :gutter="16">
            <Col :span="8">
              <Card title="资源状态">
                <Statistic title="运行状态" :value="monitoringData.status" />
                <Statistic
                  title="响应时间"
                  :value="monitoringData.responseTime"
                  suffix="ms"
                />
              </Card>
            </Col>
            <Col :span="8">
              <Card title="使用情况">
                <Statistic
                  title="使用率"
                  :value="monitoringData.usage"
                  suffix="%"
                />
                <Statistic title="并发数" :value="monitoringData.concurrent" />
              </Card>
            </Col>
            <Col :span="8">
              <Card title="性能指标">
                <Statistic
                  title="错误率"
                  :value="monitoringData.errorRate"
                  suffix="%"
                />
                <Statistic
                  title="可用性"
                  :value="monitoringData.availability"
                  suffix="%"
                />
              </Card>
            </Col>
          </Row>
        </div>
      </TabPane>
    </Tabs>

    <!-- 属性管理模态框 -->
    <Modal
      v-model:visible="propertyManagerVisible"
      title="资源属性管理"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManager
        v-if="propertyManagerVisible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性管理模态框 (useVbenForm版) -->
    <Modal
      v-model:visible="propertyManagerV2Visible"
      title="资源属性管理 (useVbenForm版)"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManagerV2
        v-if="propertyManagerV2Visible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性管理模态框 (FormCreate可视化版) -->
    <Modal
      v-model:visible="propertyManagerV3Visible"
      title="资源属性管理 (FormCreate可视化版)"
      width="95%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyManagerV3
        v-if="propertyManagerV3Visible"
        :resource="resource"
        @update="onPropertyUpdate"
      />
    </Modal>

    <!-- 属性数据编辑器模态框 -->
    <Modal
      v-model:visible="propertyDataEditorVisible"
      title="资源属性数据编辑"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <ResourcePropertyDataEditor
        v-if="propertyDataEditorVisible"
        :resource="resource"
        @update="onPropertyUpdate"
        @configureSchema="openPropertyManager"
      />
    </Modal>

    <!-- 能力配置模态框 -->
    <CapabilityConfigModal
      v-model:visible="capabilityConfigVisible"
      :capability="currentEditingCapability"
      :resource="resource"
      @save="onCapabilityConfigSave"
    />

    <!-- 能力模板库模态框 -->
    <Modal
      v-model:visible="capabilityTemplateVisible"
      title="能力模板库"
      width="80%"
      :footer="null"
      :destroy-on-close="true"
    >
      <CapabilityTemplateLibrary @select-template="onTemplateSelect" />
    </Modal>

    <!-- 使用指南模态框 -->
    <Modal
      v-model:open="capabilityGuideVisible"
      title="资源能力使用指南"
      width="90vw"
      :footer="null"
      :destroy-on-close="true"
      style="top: 20px"
    >
      <div style="height: 80vh; overflow-y: auto">
        <CapabilityManagementGuide />
      </div>
    </Modal>

    <!-- 交易管理 -->
    <ResourceTradingManager
      v-model:visible="tradingManagerVisible"
      :resource="props.resource"
      @success="onTradingUpdate"
    />

    <!-- 交易管理指南 -->
    <ResourceTradingGuide
      :visible="tradingGuideVisible"
      @update:visible="(val) => (tradingGuideVisible = val)"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';
import {
  Tabs,
  TabPane,
  Tag,
  Table,
  Row,
  Col,
  Card,
  Statistic,
  Button,
  Modal,
  message,
  Form,
  FormItem,
  Input,
  Switch,
  Select,
  SelectOption,
  InputNumber,
  Descriptions,
  DescriptionsItem,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import ResourceBasicInfo from './ResourceBasicInfo.vue';
import ResourcePropertyTab from './ResourcePropertyTab.vue';
import ResourceCapabilityTab from './ResourceCapabilityTab.vue';
import ResourceStatusManagement from '../../components/ResourceStatusManagement.vue';
import ResourcePropertyManager from './ResourcePropertyManager.vue';
import ResourcePropertyManagerV2 from './ResourcePropertyManagerV2.vue';
import ResourcePropertyManagerV3 from './ResourcePropertyManagerV3.vue';
import ResourcePropertyDataEditor from './ResourcePropertyDataEditor.vue';
import { CapabilityConfigModal } from '../../capability';
import CapabilityTemplateLibrary from '../../capability/components/CapabilityTemplateLibrary.vue';
import ResourceTradingManager from './ResourceTradingManager.vue';
import {
  CapabilityManagementGuide,
  TradingManagementGuide,
} from '../../guides';
import BehaviorManagement from '../../components/behavior/BehaviorManagement.vue';
import EventManagement from '../../components/event/EventManagement.vue';

const props = defineProps<{
  resource: any;
}>();

const emit = defineEmits<{
  'edit-capability': [capabilityKey: string];
  'capability-update': [capabilities: any];
}>();

const activeTab = ref('basic');

const tradingManagerVisible = ref(false);
const tradingGuideVisible = ref(false);

// 交易相关数据
const tradingData = ref({
  costPrice: 100,
  operationalCost: 50,
  standardPrice: 200,
  discountPrice: 150,
  monthlyPrice: 180,
  yearlyPrice: 1800,
});

const tradingPartners = ref([
  { id: 1, name: '酒店管理系统', type: 'SYSTEM', status: 'active' },
  { id: 2, name: '清洁服务团队', type: 'SERVICE', status: 'active' },
  { id: 3, name: '客户预订系统', type: 'CLIENT', status: 'active' },
]);

const tradingHistory = ref([
  {
    id: 1,
    partner: '酒店管理系统',
    type: '订阅',
    amount: 200,
    date: '2024-01-20',
  },
  {
    id: 2,
    partner: '清洁服务团队',
    type: '服务',
    amount: 50,
    date: '2024-01-19',
  },
]);

const tradingColumns = [
  { title: '合作对象', dataIndex: 'partner', key: 'partner' },
  { title: '交易类型', dataIndex: 'type', key: 'type' },
  { title: '金额', dataIndex: 'amount', key: 'amount' },
  { title: '日期', dataIndex: 'date', key: 'date' },
];

// 事件联动数据
const triggerEvents = ref([
  {
    id: 1,
    name: '数据创建',
    type: 'CREATE',
    status: 'active',
    description: '当资源属性数据被创建时触发',
    conditions: [{ id: 1, field: 'status', operator: '=', value: 'active' }],
  },
  {
    id: 2,
    name: '数据更新',
    type: 'UPDATE',
    status: 'active',
    description: '当资源属性数据被更新时触发',
    conditions: [{ id: 1, field: 'modified', operator: '>', value: '0' }],
  },
]);

const linkageRules = ref([
  {
    id: 1,
    name: '房间状态联动',
    type: 'STATUS_CHANGE',
    status: 'active',
    description: '当房间状态改变时，自动更新相关资源',
    actions: [
      { id: 1, type: 'UPDATE', targetResource: '清洁服务', action: '安排清洁' },
      { id: 2, type: 'NOTIFY', targetResource: '前台系统', action: '状态通知' },
    ],
  },
]);

// 其他数据
const resourceEvents = ref([
  {
    id: 1,
    name: '资源启动',
    type: 'START',
    status: 'completed',
    timestamp: '2024-01-20 10:00:00',
  },
  {
    id: 2,
    name: '配置更新',
    type: 'CONFIG_UPDATE',
    status: 'processing',
    timestamp: '2024-01-20 09:30:00',
  },
]);

const boundComponents = ref([
  { id: 'form_001', name: '房间预订表单', type: 'FORM', status: 'active' },
  { id: 'table_001', name: '房间状态表格', type: 'TABLE', status: 'active' },
]);

const authorizations = ref([
  { id: 1, name: '前台访问权限', type: 'READ', status: 'active' },
  { id: 2, name: '管理员权限', type: 'FULL', status: 'active' },
]);

const delegations = ref([
  { id: 1, name: '清洁服务委托', type: 'SERVICE', status: 'active' },
]);

const monitoringData = ref({
  status: '运行中',
  responseTime: 120,
  usage: 75,
  concurrent: 15,
  errorRate: 0.1,
  availability: 99.9,
});

// 计算属性

// 事件表格列配置
const eventColumns = [
  { title: '事件名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '状态', dataIndex: 'status', key: 'status' },
  { title: '时间', dataIndex: 'timestamp', key: 'timestamp' },
];

// 基础信息相关方法
const handleBasicInfoEdit = (resource: any) => {
  message.info('编辑基础信息功能待实现');
  console.log('编辑基础信息:', resource);
};

const handlePropertyUpdate = (properties: any) => {
  message.success('属性更新成功');
  console.log('属性更新:', properties);
  // 这里可以处理属性更新后的逻辑
};

const handleCapabilityUpdate = (capabilities: any) => {
  message.success('能力更新成功');
  console.log('能力更新:', capabilities);
  emit('capability-update', capabilities);
};

const handleEditCapability = (capabilityKey: string) => {
  console.log('编辑能力:', capabilityKey);
  emit('edit-capability', capabilityKey);
};

const editBasicInfo = () => {
  message.info('编辑基础信息功能待实现');
};

// 方法

const onTradingUpdate = (data: any) => {
  message.success('交易配置更新成功');
  // 这里可以处理交易更新后的逻辑
  console.log('交易更新:', data);
};

// 切换能力启用状态
const toggleCapability = (capabilityKey: string) => {
  console.log('切换能力状态被调用，参数:', capabilityKey);

  if (!props.resource?.capabilities) {
    message.error('资源能力配置不存在');
    return;
  }

  try {
    const caps = JSON.parse(props.resource.capabilities);
    console.log('当前能力配置:', caps);

    let updatedCaps;
    if (Array.isArray(caps)) {
      // 新格式：数组格式
      updatedCaps = caps.map((cap: any) => {
        if (cap.id === capabilityKey) {
          return { ...cap, enabled: !cap.enabled };
        }
        return cap;
      });
    } else {
      // 旧格式：对象格式
      if (caps[capabilityKey]) {
        updatedCaps = { ...caps };
        updatedCaps[capabilityKey] = {
          ...updatedCaps[capabilityKey],
          enabled: !updatedCaps[capabilityKey].enabled,
          enabledenabled,
        };
      } else {
        message.error('未找到该能力的配置');
        return;
      }
    }

    console.log('更新后的能力配置:', updatedCaps);

    // 通过emit通知父组件更新
    emit('capability-update', updatedCaps);

    const capabilityName = Array.isArray(caps)
      ? caps.find((cap: any) => cap.id === capabilityKey)?.name || capabilityKey
      : getCapabilityName(capabilityKey);
    capabilityNameArray.isArraycaps.findcap.idcapabilityKey
      ?.namecapabilityKeycapabilityNameArray.isArraycaps.findcap.idcapabilityKey
      ?.namecapabilityKey;

    const isEnabled = Array.isArray(updatedCaps)
      ? updatedCaps.find((cap: any) => cap.id === capabilityKey)?.enabled
      : updatedCaps[capabilityKey]?.enabled;
    constisEnabledArray.isArrayupdatedCaps.findcap.idcapabilityKey
      ?.enabledisEnabledArray.isArrayupdatedCaps.findcap.idcapabilityKey
      ?.enabled;

    message.success(`${capabilityName}已${isEnabled ? '启用' : '禁用'}`);
  } catch (error) {
    console.error('切换能力状态失败:', error);
    message.error('操作失败');
  }
};

// 编辑能力配置
const editCapability = (capabilityKey: string) => {
  console.log('编辑能力配置被调用，参数:', capabilityKey);
  console.log('当前资源:', props.resource);
  console.log('当前资源能力:', props.resource?.capabilities);

  // 从资源的能力配置中找到对应的能力
  if (props.resource && props.resource.capabilities) {
    try {
      const capabilities = JSON.parse(props.resource.capabilities);
      console.log('解析后的能力配置:', capabilities);

      // 支持数组格式（新格式）和对象格式（旧格式）
      let capabilityConfig;
      if (Array.isArray(capabilities)) {
        // 新格式：数组格式
        capabilityConfig = capabilities.find(
          (cap: any) => cap.id === capabilityKey,
        );
        console.log('从数组中查找的能力配置:', capabilityConfig);
      } else {
        // 旧格式：对象格式
        capabilityConfig = capabilities[capabilityKey];
        console.log('从对象中查找的能力配置:', capabilityConfig);
      }

      if (capabilityConfig) {
        // 构建完整的能力对象
        const capability = {
          id: capabilityConfig.id || capabilityKey,
          name: capabilityConfig.name || getCapabilityName(capabilityKey),
          description:
            capabilityConfig.description ||
            getCapabilityDescription(capabilityKey),
          type: capabilityConfig.type || 'business',
          enabled: capabilityConfig.enabled !== false,
          priority: capabilityConfig.priority || 50,
          version: capabilityConfig.version || '1.0.0',
          icon: capabilityConfig.icon || getCapabilityIcon(capabilityKey),
          color: capabilityConfig.color || getCapabilityColor(capabilityKey),
          tags: capabilityConfig.tags || [],
          implementation: capabilityConfig.implementation || {},
          preconditions: capabilityConfig.preconditions || {},
          stateMachine: capabilityConfig.stateMachine || {},
          eventSystem: capabilityConfig.eventSystem || {},
          behaviorExecution: capabilityConfig.behaviorExecution || {},
        };
        console.log('构建的能力对象:', capability);
        currentEditingCapability.value = capability;
        capabilityConfigVisible.value = true;
        console.log('模态框已打开');
      } else {
        console.error('未找到能力配置:', capabilityKey);
        message.error('未找到该能力的配置信息');
      }
    } catch (error) {
      console.error('解析能力配置失败:', error);
      message.error('解析能力配置失败');
    }
  } else {
    console.error('资源或能力配置不存在');
    message.error('资源能力配置不存在');
  }
};

// 删除能力
const removeCapability = (capabilityKey: string) => {
  console.log('删除能力被调用，参数:', capabilityKey);

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除能力"${getCapabilityName(capabilityKey)}"吗？`,
    onOk: () => {
      if (!props.resource?.capabilities) {
        message.error('资源能力配置不存在');
        return;
      }

      try {
        const caps = JSON.parse(props.resource.capabilities);
        console.log('当前能力配置:', caps);

        let updatedCaps;
        let capabilityName;

        if (Array.isArray(caps)) {
          // 新格式：数组格式
          const capability = caps.find((cap: any) => cap.id === capabilityKey);
          if (capability) {
            capabilityName = capability.name || capabilityKey;
            updatedCaps = caps.filter((cap: any) => cap.id !== capabilityKey);
          } else {
            message.error('未找到该能力的配置');
            return;
          }
        } else {
          // 旧格式：对象格式
          if (caps[capabilityKey]) {
            capabilityName = getCapabilityName(capabilityKey);
            updatedCaps = { ...caps };
            delete updatedCaps[capabilityKey];
          } else {
            message.error('未找到该能力的配置');
            return;
          }
        }

        console.log('删除后的能力配置:', updatedCaps);

        // 通过emit通知父组件更新
        emit('capability-update', updatedCaps);

        message.success(`${capabilityName}已删除`);
      } catch (error) {
        console.error('删除能力失败:', error);
        message.error('删除失败');
      }
    },
  });
};

const showCapabilityGuide = () => {
  capabilityGuideVisible.value = true;
};

const showTradingGuide = () => {
  tradingGuideVisible.value = true;
};

const configureTrading = () => {
  tradingManagerVisible.value = true;
};

const configureEventLinkage = () => {
  message.info('事件联动配置功能开发中');
};

const bindComponent = () => {
  message.info('组件绑定功能开发中');
};

const grantAuthorization = () => {
  message.info('授权管理功能开发中');
};

const createDelegation = () => {
  message.info('委托管理功能开发中');
};

const configureMonitoring = () => {
  message.info('监控配置功能开发中');
};

// 工具方法 - 解析能力数据
const parseCapabilities = (capabilitiesStr: string) => {
  if (!capabilitiesStr) return [];
  try {
    const capabilities = JSON.parse(capabilitiesStr);
    // 如果是数组格式（新格式），直接返回
    if (Array.isArray(capabilities)) {
      return capabilities;
    }
    // 如果是对象格式（旧格式），转换为数组
    if (typeof capabilities === 'object') {
      return Object.entries(capabilities).map(([id, config]) => ({
        id,
        name: id, // 旧格式没有name，使用id作为name
        enabled: (config as any).enabled || false,
        priority: (config as any).priority || 50,
      }));
    }
    return [];
  } catch {
    return [];
  }
};

// 获取能力名称（兼容旧格式）
const getCapabilityName = (capability: any) => {
  if (capability.name) return capability.name;
  if (capability.id) return capability.id;
  return '未知能力';
};

// 获取能力描述（兼容旧格式）
const getCapabilityDescription = (capability: any) => {
  if (capability.description) return capability.description;
  return '';
};

// 获取能力图标（兼容旧格式）
const getCapabilityIcon = (capability: any) => {
  if (capability.icon) return capability.icon;
  return 'ant-design:setting-outlined';
};

// 获取能力颜色（兼容旧格式）
const getCapabilityColor = (capability: any) => {
  if (capability.color) return capability.color;
  return '#666';
};

const getCapabilityLabel = (key: string) => {
  const labels: Record<string, string> = {
    FORM: '表单能力',
    TABLE: '表格能力',
    WORKFLOW: '流程能力',
    RULE: '规则能力',
    API: 'API能力',
    AUTH: '授权能力',
    EVENT: '事件能力',
    DELEGATE: '委托能力',
  };
  return labels[key] || key;
};

const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    api: 'API接口',
    service: '服务调用',
    workflow: '工作流',
    rule: '规则引擎',
  };
  return labels[type] || type;
};

const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    api: 'blue',
    service: 'green',
    workflow: 'purple',
    rule: 'orange',
  };
  return colors[type] || 'default';
};

const getComponentIcon = (type: string) => {
  const icons: Record<string, string> = {
    FORM: 'ant-design:form-outlined',
    TABLE: 'ant-design:table-outlined',
    WORKFLOW: 'ant-design:deployment-unit-outlined',
    RULE: 'ant-design:setting-outlined',
    API: 'ant-design:api-outlined',
  };
  return icons[type] || 'ant-design:appstore-outlined';
};

const getAuthTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    READ: 'ant-design:eye-outlined',
    WRITE: 'ant-design:edit-outlined',
    FULL: 'ant-design:safety-outlined',
  };
  return icons[type] || 'ant-design:key-outlined';
};

const getDelegationTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    SERVICE: 'ant-design:service-outlined',
    MANAGEMENT: 'ant-design:team-outlined',
    OPERATION: 'ant-design:tool-outlined',
  };
  return icons[type] || 'ant-design:user-switch-outlined';
};

const getPartnerTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    SYSTEM: 'ant-design:laptop-outlined',
    SERVICE: 'ant-design:service-outlined',
    CLIENT: 'ant-design:user-outlined',
  };
  return icons[type] || 'ant-design:team-outlined';
};

const getEventTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    CREATE: 'ant-design:plus-circle-outlined',
    UPDATE: 'ant-design:edit-outlined',
    DELETE: 'ant-design:delete-outlined',
  };
  return icons[type] || 'ant-design:notification-outlined';
};

const getRuleTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    STATUS_CHANGE: 'ant-design:swap-outlined',
    DATA_CHANGE: 'ant-design:database-outlined',
    USER_ACTION: 'ant-design:user-outlined',
  };
  return icons[type] || 'ant-design:setting-outlined';
};

const getActionTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    UPDATE: 'ant-design:edit-outlined',
    NOTIFY: 'ant-design:notification-outlined',
    CREATE: 'ant-design:plus-outlined',
  };
  return icons[type] || 'ant-design:tool-outlined';
};
</script>

<style lang="less" scoped>
.resource-self-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .resource-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    .resource-info {
      display: flex;
      align-items: center;
      gap: 16px;

      .resource-icon {
        font-size: 32px;
        color: #1890ff;
      }

      .resource-details {
        h2 {
          margin: 0 0 4px 0;
          font-size: 20px;
          font-weight: 600;
        }

        .resource-code {
          margin: 0 0 4px 0;
          color: #666;
          font-family: monospace;
        }

        .resource-description {
          margin: 0;
          color: #999;
          font-size: 14px;
        }
      }
    }
  }

  .tab-content {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }

      .header-actions {
        display: flex;
        gap: 8px;
      }
    }

    h4 {
      margin: 24px 0 16px 0;
      font-size: 14px;
      font-weight: 600;
      color: #333;
    }
  }

  .properties-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;

    .property-item {
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      background: #fafafa;

      .property-label {
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }

      .property-value {
        color: #666;
        word-break: break-all;
      }
    }
  }

  .capabilities-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;

    .capability-item {
      padding: 16px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fff;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        border-color: #1890ff;
      }

      .capability-header {
        display: flex;
        align-items: flex-start;
        gap: 12px;

        .anticon {
          font-size: 20px;
          color: #1890ff;
          margin-top: 2px;
        }

        .capability-info {
          flex: 1;

          .capability-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 4px;
          }

          .capability-desc {
            font-size: 12px;
            color: #666;
            margin-bottom: 8px;
            line-height: 1.4;
          }

          .capability-meta {
            display: flex;
            gap: 8px;
            align-items: center;
          }
        }

        .capability-actions {
          display: flex;
          flex-direction: column;
          gap: 4px;
          margin-left: auto;

          .ant-btn {
            padding: 2px 8px;
            height: auto;
            font-size: 12px;
          }
        }
      }
    }
  }

  .pricing-section {
    margin-bottom: 24px;
  }

  .partners-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
    margin-bottom: 24px;

    .partner-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fff;

      .anticon {
        font-size: 20px;
        color: #1890ff;
      }

      .partner-info {
        flex: 1;

        .partner-name {
          font-weight: 600;
          color: #333;
        }

        .partner-type {
          font-size: 12px;
          color: #666;
        }
      }
    }
  }

  .events-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 16px;
    margin-bottom: 24px;

    .event-item {
      padding: 16px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fff;

      .event-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        .anticon {
          font-size: 16px;
          color: #1890ff;
        }

        .event-name {
          font-weight: 600;
          flex: 1;
        }
      }

      .event-description {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
      }

      .event-conditions {
        .condition-item {
          display: flex;
          font-size: 12px;
          margin-bottom: 4px;

          .condition-label {
            font-weight: 500;
            min-width: 80px;
            color: #666;
          }

          .condition-value {
            color: #333;
          }
        }
      }
    }
  }

  .rules-list {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .rule-item {
      padding: 16px;
      border: 1px solid #f0f0f0;
      border-radius: 8px;
      background: #fff;

      .rule-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        .anticon {
          font-size: 16px;
          color: #722ed1;
        }

        .rule-name {
          font-weight: 600;
          flex: 1;
        }
      }

      .rule-description {
        font-size: 12px;
        color: #666;
        margin-bottom: 8px;
      }

      .rule-actions {
        .action-item {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 12px;
          margin-bottom: 4px;

          .anticon {
            font-size: 12px;
            color: #52c41a;
          }
        }
      }
    }
  }

  .components-list,
  .authorization-list,
  .delegation-list {
    display: flex;
    flex-direction: column;
    gap: 12px;

    .component-item,
    .authorization-item,
    .delegation-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px;
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      background: #fff;

      .anticon {
        font-size: 16px;
        color: #1890ff;
      }
    }
  }

  .monitoring-dashboard {
    .ant-card {
      margin-bottom: 16px;
    }
  }
}
</style>
